package com.dxyxx.framework;

import java.io.IOException;
import java.util.List;

import org.apache.http.Header;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.JavaType;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import br.com.pierry.simpletoast.SimpleToast;

import com.android.customized.KenBurnsView;
import com.android.customized.ObservableScrollView;
import com.android.customized.ObservableScrollView.ScrollViewListener;
import com.dxyxx.R;
import com.dxyxx.android.setting.SettingActivity;
import com.dxyxx.android.setting.UserPreferences;
import com.dxyxx.dialog.AgainPlayer;
import com.dxyxx.framework.CAS.CallBack;
import com.dxyxx.pojo.Auxiliary;
import com.dxyxx.pojo.ProductDetailItem;
import com.dxyxx.pojo.ResponseResult;
import com.dxyxx.pojo.User;
import com.http.HttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nineoldandroids.view.ViewHelper;
import com.ta.utdid2.android.utils.StringUtils;

/**
 * 这个地方也用数据监听吧。
 * 
 * @author Administrator
 * 
 */
public class MyCenterFragment extends BaseFragment {
	private View mHeader;
	private KenBurnsView mHeaderPicture;
	private ObservableScrollView scrollView;
	private AccelerateDecelerateInterpolator mSmoothInterpolator;

	private RectF mRect1 = new RectF();
	private RectF mRect2 = new RectF();
	private ImageView mHeaderLogo;
	private View emptyView;
	private int mHeaderHeight;
	private int mMinHeaderTranslation;
	private User user;
	private TextView username;
	private TextView integralText;
	private TextView balanceText;
	private TextView bufferText;
	private ImageView myimage;
	private UserPreferences userPreferences;
	private ImageView refreshImage;
	private Animation anim;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.activity_mycenter, container, false);

		mHeaderHeight = getResources().getDimensionPixelSize(R.dimen.header_height);
		mMinHeaderTranslation = -mHeaderHeight + getResources().getDimensionPixelSize(R.dimen.min_header_size);

		mSmoothInterpolator = new AccelerateDecelerateInterpolator();
		scrollView = (ObservableScrollView) view.findViewById(R.id.scrollview);
		mHeader = view.findViewById(R.id.header);
		emptyView = (View) view.findViewById(R.id.empty_layout);
		mHeaderPicture = (KenBurnsView) view.findViewById(R.id.header_picture);
		mHeaderPicture.setResourceIds(R.drawable.personal_center, R.drawable.personal_center);
		mHeaderLogo = (ImageView) view.findViewById(R.id.header_logo);
		// 积分 余额  待提货
		integralText = (TextView) view.findViewById(R.id.integralText);
		balanceText = (TextView) view.findViewById(R.id.balanceText);
		bufferText = (TextView) view.findViewById(R.id.bufferText);
		ScrollViewListener scrollViewListener = new ScrollViewListener() {

			//			@SuppressLint("NewApi")
			@Override
			public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {

				//				mHeader.setTranslationY(Math.max(-y, mMinHeaderTranslation));
				ViewHelper.setTranslationY(mHeader, Math.max(-y, mMinHeaderTranslation));
				//				float ratio = clamp(mHeader.getTranslationY() / mMinHeaderTranslation, 0.0f, 1.0f);
				float ratio = clamp(ViewHelper.getTranslationY(mHeader) / mMinHeaderTranslation, 0.0f, 1.0f);

				interpolate(mHeaderLogo, emptyView, mSmoothInterpolator.getInterpolation(ratio));
			}
		};

		scrollView.setScrollViewListener(scrollViewListener);

		RelativeLayout rl = (RelativeLayout) view.findViewById(R.id.personal_order_layout);
		rl.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				CAS call = new CAS(getActivity(), RequestCode.MyOrder, new CallBack() {
					@Override
					public void method() {
						startActivity(new Intent(getActivity(), OrderListActivity.class));
					}
				});
				call.call();
			}
		});
		scrollView.setScrollViewListener(scrollViewListener);

		RelativeLayout r2 = (RelativeLayout) view.findViewById(R.id.personal_group_layout);
		r2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				CAS call = new CAS(getActivity(), RequestCode.MyGroupOrder, new CallBack() {
					@Override
					public void method() {
						startActivity(new Intent(getActivity(), TicketActivity.class));
					}
				});
				call.call();
			}
		});
		RelativeLayout r3 = (RelativeLayout) view.findViewById(R.id.personal_qr_layout);
		r3.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				CAS call = new CAS(getActivity(), RequestCode.MyQr, new CallBack() {
					@Override
					public void method() {
						startActivity(new Intent(getActivity(), ScanActivity.class));
					}
				});
				call.call();
			}
		});

		// 处理个人信息。。积分押后，余额押后，待提货 押后
		username = (TextView) view.findViewById(R.id.username);
		myimage = (ImageView) view.findViewById(R.id.header_logo);
		refreshImage = (ImageView) view.findViewById(R.id.refreshImageButton);
		userPreferences = UserPreferences.getInstance(getActivity());
		anim = AnimationUtils.loadAnimation(getActivity(), R.anim.round_loading);
		user = userPreferences.getCurrentUser();
		setUserInfoOnView(user);// 放心，这里的user绝对是全的
		refreshImage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// 归零、 重新更新积分
				callAuxiliryTime = 0;

				callAuxiliry();
			}
		});
		//点击头像登陆，或者 点击头像修改信息
		myimage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				user = userPreferences.getCurrentUser();
				if (user.getPhone() != null) {
					// 开启修改信息的activity
					//					CAS call = new CAS(getActivity(), RequestCode.Login, new CallBack() {
					//						@Override
					//						public void method() {
					//不用cas了，资料应该都是全的。
					startActivityForResult(new Intent(getActivity(), InfoActivity.class), 1);
					//						}
					//					});
					//					call.call();
				} else {
					// 没有登录。 此处不能用cas，直接 调用登陆界面
					Intent intent = new Intent(getActivity(), LoginActivity.class);
					intent.putExtra("relogin", false);
					startActivityForResult(intent, RequestCode.Login);
				}
			}
		});
		//注册用户信息监听
		//getActivity().getContentResolver().registerContentObserver(UserDataChangeProvider.CONTENT_URI, true, new UserDataContentObserver(null, getActivity(),username));
		//设置
		view.findViewById(R.id.settingImageButton).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				startActivityForResult(new Intent(getActivity(), SettingActivity.class), 1);

			}
		});
		// 更新 积分
		callAuxiliry();
		return view;
	}

	private int callAuxiliryTime = 0;

	private void callAuxiliry() {
		refreshImage.startAnimation(anim);
		refreshImage.setClickable(false);// 禁止重复发送。
		if (callAuxiliryTime < 2) {
			// 默默加载，刷新 积分等数据
			HttpUtil.get("auxiliary/get", new AsyncHttpResponseHandler() {

				@Override
				public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {

					try {
						JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, Auxiliary.class);
						ResponseResult<Auxiliary> rr = getObjectMapper().readValue(arg2, javaType);
						if (rr.getCode() == -1) {
							//登陆 
							String urlString = "login";
							RequestParams params = new RequestParams();
							User user = userPreferences.getCurrentUser();
							if (user.getPhone() != null) {//user 不会是null
								params.add("phone", user.getPhone());
								params.add("password", user.getPassword());
							}
							HttpUtil.post(urlString, params, new AsyncHttpResponseHandler() {
								@Override
								public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
									//不管
								}

								@Override
								public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
									// 更新数据 数据到 文件。
									try {
										JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, User.class);
										ResponseResult<User> rr = getObjectMapper().readValue(arg2, javaType);
										// 存储 数据到 文件。
										if (rr.getCode() == 1) {
											// 重新 callAuxiliry
											callAuxiliryTime++;// 控制 访问 次数
											callAuxiliry();
										} else {
											//登录失败，什么都不做
										}
									} catch (Exception e) {
										e.printStackTrace();
									}

								}

							});
						} else if (rr.getCode() == 1) {
							//s更新数据。 
							//SimpleToast.ok(getActivity(), "更新积分成功");
							integralText.setText(rr.getObject().getIntegral() + "");
							balanceText.setText(rr.getObject().getBalance() + "");
							bufferText.setText(rr.getObject().getBuffer() + "");
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
					// 报错不处理
				}

				@Override
				public void onFinish() {
					refreshImage.setClickable(true);
					refreshImage.clearAnimation();
					super.onFinish();
				}

			});
		}
	}

	//	@SuppressLint("NewApi")
	private void interpolate(View view1, View view2, float interpolation) {
		getOnScreenRect(mRect1, view1);
		getOnScreenRect(mRect2, view2);

		float scaleX = 1.0F + interpolation * (mRect2.width() / mRect1.width() - 1.0F);
		float scaleY = 1.0F + interpolation * (mRect2.height() / mRect1.height() - 1.0F);
		float translationX = 0.5F * (interpolation * (mRect2.left + mRect2.right - mRect1.left - mRect1.right));
		float translationY = 0.5F * (interpolation * (mRect2.top + mRect2.bottom - mRect1.top - mRect1.bottom));

		//		view1.setTranslationX(translationX);
		//		view1.setTranslationY(translationY - mHeader.getTranslationY());
		//		view1.setScaleX(scaleX);
		//		view1.setScaleY(scaleY);

		ViewHelper.setTranslationX(view1, translationX);
		ViewHelper.setTranslationY(view1, translationY - ViewHelper.getTranslationY(mHeader));
		ViewHelper.setScaleX(view1, scaleX);
		ViewHelper.setScaleY(view1, scaleY);
	}

	private RectF getOnScreenRect(RectF rect, View view) {

		rect.set(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
		return rect;
	}

	public static float clamp(float value, float max, float min) {
		return Math.max(Math.min(value, min), max);
	}

	protected void callNetwork() {
		refreshImage.startAnimation(anim);
		refreshImage.setClickable(false);// 禁止重复发送。
		String urlString = "user/look";
		HttpUtil.get(urlString, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				refreshImage.setClickable(true);
				try {
					JavaType javaType = getObjectMapper().getTypeFactory().constructParametricType(ResponseResult.class, User.class);

					ResponseResult<User> rr = getObjectMapper().readValue(new String(arg2), javaType);
					//得到 user 详细信息
					if (rr.getCode() == 1) {
						user = rr.getObject();
						userPreferences.updateUser(rr.getObject());
						setUserInfoOnView(user);
					} else {
						SimpleToast.info(getActivity(), "更新个人信息失败");
					}
				} catch (JsonParseException e) {
					e.printStackTrace();
				} catch (JsonMappingException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					refreshImage.clearAnimation();
				}

			}

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				refreshImage.setClickable(true);
				AgainPlayer againPlayer = new AgainPlayer(getActivity(), new com.dxyxx.dialog.AgainPlayer.CallBack() {

					@Override
					public void method() {
						callNetwork();
					}
				});
				againPlayer.call("貌似没网了！");
				refreshImage.clearAnimation();
			}
		});
	}

	protected void setUserInfoOnView(User user) {
		if (user.getPhone() != null) {
			username.setText("Hi, " + user.getUsername());
			if (!StringUtils.isEmpty(user.getImage())) {
				imageLoader.displayImage(baseImageURL + user.getImage() + "?p=0", myimage, squareOptions, null);
			}
		} else {
			username.setText("点击头像登陆吧！ ");
		}
	}

}
